<template>
  <div>
    <el-card>
      <!-- 顶部操作栏 -->
      <div style="margin-bottom: 20px; display: flex; justify-content: space-between;">
        <el-button type="primary" icon="el-icon-plus" @click="handleAdd">新增用户</el-button>
        <el-input
          v-model="searchKeyword"
          placeholder="搜索用户名或姓名"
          clearable
          @clear="fetchData"
          @keyup.enter.native="fetchData"
          style="width: 300px;"
        />
      </div>

      <!-- 用户表格 -->
      <el-table :data="tableData" border stripe empty-text="暂无数据">
        <el-table-column type="index" label="序号" width="50" />
        <el-table-column prop="username" label="用户名" />
        <el-table-column prop="name" label="姓名" />
        <el-table-column prop="role" label="角色" >
          <template v-slot="scope">
            <el-tag type="danger" v-if="scope.row.role !== 'user'">管理员</el-tag>
            <el-tag type="success" v-else>普通用户</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" />
        <el-table-column label="操作" width="180">
          <template slot-scope="scope">
            <el-button size="mini" type="primary" @click="handleEdit(scope.row)">编辑</el-button>
            <el-button size="mini" type="danger" @click="handleDelete(scope.row.userId)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <el-pagination
        background
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        :page-size="pageSize"
        :page-sizes="[10, 20, 30, 100]"
        :current-page="page"
        @current-change="handleCurrentChange"
        @size-change="handleSizeChange"
        style="margin-top: 20px; text-align: right;"
      />
    </el-card>

    <!-- 弹窗表单 -->
    <el-dialog :title="dialogTitle" :visible.sync="dialogVisible" width="500px">
      <el-form :model="userForm" :rules="rules" ref="userForm" label-width="100px">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="userForm.username" :disabled="userForm.userId"/>
        </el-form-item>
        <el-form-item label="姓名" prop="name">
          <el-input v-model="userForm.name" />
        </el-form-item>
        <el-form-item label="密码" prop="password" v-if="!userForm.userId">
          <el-input v-model="userForm.password" type="password" />
        </el-form-item>
        <el-form-item label="角色" prop="role">
          <el-select v-model="userForm.role" placeholder="请选择角色">
            <el-option label="管理员" value="admin" />
            <el-option label="普通用户" value="user" />
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  fetchUserList,
  createUser,
  updateUser,
  deleteUser
} from '@/api/userInfo'

export default {
  data() {
    return {
      tableData: [],
      total: 0,
      page: 1,
      pageSize: 10,
      dialogVisible: false,
      dialogTitle: '新增用户',
      searchKeyword: '',
      userForm: {
        userId: null,
        username: '',
        name: '',
        password: '',
        role: 'user'
      },
      rules: {
        username: [{ required: true, message: '请输入用户名', trigger: 'blur' }],
        name: [{ required: true, message: '请输入姓名', trigger: 'blur' }],
        password: [{ required: true, message: '请输入密码', trigger: 'blur' }],
        role: [{ required: true, message: '请选择角色', trigger: 'change' }]
      }
    }
  },
  created() {
    this.fetchData()
  },
  methods: {
    fetchData() {
      fetchUserList({
        page: this.page,
        pageSize: this.pageSize,
        keyword: this.searchKeyword
      }).then(res => {
        this.tableData = res.records
        this.total = res.total*1
      })
    },
    handleSizeChange(val) {
      this.pageSize = val
      this.fetchData()
    },
    handleCurrentChange(val) {
      this.page = val
      this.fetchData()
    },
    handleAdd() {
      this.dialogTitle = '新增用户'
      this.userForm = {
        userId: null,
        username: '',
        name: '',
        password: '',
        role: 'user'
      }
      this.dialogVisible = true
    },
    handleEdit(row) {
      this.dialogTitle = '编辑用户信息'
      this.userForm = {
        userId: row.userId,
        username: row.username,
        name: row.name,
        role: row.role
      }
      this.dialogVisible = true
    },
    handleDelete(id) {
      this.$confirm('确定删除该用户吗？', '提示', {
        type: 'warning'
      }).then(() => {
        deleteUser(id).then(() => {
          this.$message.success('删除成功')
          this.fetchData()
        })
      }).catch(() => {})
    },
    handleSubmit() {
      this.$refs.userForm.validate(valid => {
        if (valid) {
          if (this.userForm.userId) {
            updateUser(this.userForm).then(() => {
              this.$message.success('更新成功')
              this.dialogVisible = false
              this.fetchData()
            })
          } else {
            createUser(this.userForm).then(() => {
              this.$message.success('新增成功')
              this.dialogVisible = false
              this.fetchData()
            })
          }
        }
      })
    }
  }
}
</script>
